package com.sls.api.game.servlet.downstream;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sls.api.game.constant.Constant;
import com.sls.api.game.constant.ExCodeDes;
import com.sls.api.game.page.Pagination;
import com.sls.api.game.pojo.Goods;
import com.sls.api.game.pojo.UserInfo;
import com.sls.api.game.servlet.SuperServlet;
import com.sls.api.util.IpUtil;
import com.sls.api.util.OrganizeRespXmlData;
import com.sls.api.util.ResponseDataXmlFormat;
import com.sls.api.util.SecretKeyUtil;
import com.sls.api.util.UtilMD5Encryption;
import com.sls.core.common.CommonUtil;
import com.sls.core.socket.Head;
import com.sls.core.socket.SocketDTO;

/**
 * 具体商品同步
 * 
 * @author cx
 * 
 */
public class SpecificGoodsSyncServlet extends SuperServlet {
	private static final long serialVersionUID = 3259421706359757990L;
	private static Logger log = Logger
			.getLogger(SpecificGoodsSyncServlet.class);
	private String resCode;
	private String resMsg;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setAttribute("org.eclipse.jetty.server.Request.queryEncoding",
				"UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		resp.setStatus(HttpServletResponse.SC_OK);

		// 合作方用户账号
		String userNo = req.getParameter("userNo");
		if (StringUtils.isNotEmpty(userNo)) {
			userNo = userNo.trim();
		}
		// 商品品牌编号
		String brandId = req.getParameter("brandId");
		if (StringUtils.isNotEmpty(brandId)) {
			brandId = brandId.trim();
		}
		// 签名字符串
		String sign = req.getParameter("sign");
		if (StringUtils.isNotEmpty(sign)) {
			sign = sign.trim();
		}

		boolean flag = this.validateData(userNo, brandId, sign, resp, req);
		if (flag) {
			try {
				List<Goods> goods = this.queryAllGoods(userNo, brandId, req);
				if (goods == null) {
					ResponseDataXmlFormat.returnFailMsg(
							ExCodeDes.UNKNOW_ERROR.getCode(),
							ExCodeDes.UNKNOW_ERROR.getDescription(), resp);
					return;
				}
				String xmlData = OrganizeRespXmlData.assembleXmlForGoodsSync(
						resCode, resMsg, goods);
				resp.getWriter().write(xmlData);
				resp.getWriter().flush();
				resp.getWriter().close();
			} catch (Exception e) {
				log.error(e);
				ResponseDataXmlFormat.returnFailMsg(
						ExCodeDes.UNKNOW_ERROR.getCode(),
						ExCodeDes.UNKNOW_ERROR.getDescription(), resp);
			}
		}
	}

	/**
	 * 查询同一品牌下的所有商品
	 * 
	 * @param userNo
	 * @param brandId
	 * @param req
	 * @return
	 * @throws Exception
	 */
	private List<Goods> queryAllGoods(String userNo, String brandId,
			HttpServletRequest req) throws Exception {
		UserInfo query = new UserInfo();
		query.setCurrentPage(1);
		query.setPageSize(20);
		query.setUserNo(userNo);
		query.setGoodsCategoryId(brandId);

		List<Goods> goodsList = new LinkedList<Goods>();
		Pagination<Goods> page = queryPage(req, query);
		if (page != null) {
			if (page.getList() != null) {
				goodsList.addAll(page.getList());
			}
			int count = page.getRowCount();
			if (query.getPageSize() == 0) {
				query.setPageSize(1);
			}
			for (int i = 1; i < Math.ceil(count * 1.0 / query.getPageSize()); i++) {
				query.setCurrentPage(i + 1);
				page = queryPage(req, query);
				if (!Constant.SUCCESS.equals(resCode)) {
					break;
				}
				if (page.getList() != null) {
					goodsList.addAll(page.getList());
				}
			}
			return goodsList;
		}
		return null;

	}

	/**
	 * 分批查询
	 * 
	 * @param req
	 * @param query
	 * @return
	 * @throws Exception
	 */
	private Pagination<Goods> queryPage(HttpServletRequest req, UserInfo query)
			throws Exception {
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(Constant.QUERY_GOODS_BY_BRAND_ID);
		head.setIp(IpUtil.getIpAddr(req));
		head.setUserId(query.getUserNo());
		SocketDTO dto = super.send(head, query);
		Gson gson = CommonUtil.gson();
		if (dto != null && dto.getHead() != null
				&& Constant.SUCCESS.equals(dto.getHead().getResponseCode())) {
			Head head2 = dto.getHead();
			resCode = head2.getResponseCode();
			resMsg = head2.getResponseMessage();
			String body = dto.getBody();
			log.info(body);
			Pagination<Goods> goods = gson.fromJson(body,
					new TypeToken<Pagination<Goods>>() {
					}.getType());
			return goods;
		}
		return null;
	}

	/**
	 * 数据校验
	 * 
	 * @param userId
	 * @param userPwd
	 * @param sign
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	private boolean validateData(String userNo, String brandId, String sign,
			HttpServletResponse resp, HttpServletRequest req)
			throws IOException {
		boolean result = false;
		if (StringUtils.isEmpty(userNo)) {
			log.info("商品同步时,合作方用户账号为空!!!");
			ResponseDataXmlFormat.returnFailMsg(
					ExCodeDes.PARAMETER_EMPTY.getCode(),
					ExCodeDes.PARAMETER_EMPTY.getDescription() + "[userId]!",
					resp);
			return false;
		} else if (StringUtils.isEmpty(brandId)) {
			log.info("商品同步时,商品品牌编号为空!!!");
			ResponseDataXmlFormat.returnFailMsg(
					ExCodeDes.PARAMETER_EMPTY.getCode(),
					ExCodeDes.PARAMETER_EMPTY.getDescription() + "[brandId]!",
					resp);
			return false;
		} else if (StringUtils.isEmpty(sign)) {
			log.info("商品同步时,签名字符串为空!!!");
			ResponseDataXmlFormat.returnFailMsg(
					ExCodeDes.PARAMETER_EMPTY.getCode(),
					ExCodeDes.PARAMETER_EMPTY.getDescription() + "[sign]!",
					resp);
			return false;
		} else {
			StringBuilder builder = new StringBuilder();
			builder.append(userNo);
			builder.append(brandId);
			String secretKey = SecretKeyUtil.getInstance().getKey(userNo, req);
			if (StringUtils.isNotEmpty(secretKey)) {
				builder.append(secretKey);
			} else {
				ResponseDataXmlFormat.returnFailMsg(
						ExCodeDes.UNKNOW_ERROR.getCode(),
						ExCodeDes.UNKNOW_ERROR.getDescription(), resp);
				return false;
			}
			String data = builder.toString();

			boolean checked = UtilMD5Encryption.checkMD5SignatureOfUTF8(data,
					sign);
			if (checked) {
				result = true;
			} else {
				log.info("商品同步时,数字签名验证失败!!!");
				ResponseDataXmlFormat.returnFailMsg(
						ExCodeDes.SIGN_FAIL.getCode(),
						ExCodeDes.SIGN_FAIL.getDescription(), resp);
				return false;
			}
		}
		if (StringUtils.isNotEmpty(brandId)) {
			boolean f = this.goodsBrandExist(brandId, userNo, req);
			if (!f) {
				log.info("商品同步时,商品品牌编号不存在!!!");
				ResponseDataXmlFormat.returnFailMsg(
						ExCodeDes.GOODS_BRAND_NOT_EXIST.getCode(),
						ExCodeDes.GOODS_BRAND_NOT_EXIST.getDescription(), resp);
				return false;
			} else {
				result = true;
			}
		}
		return result;
	}

	/**
	 * 判断此商品品牌是否存在
	 * 
	 * @param goodsId
	 * @param userId
	 * @param req
	 * @return
	 */
	private boolean goodsBrandExist(String brandId, String userNo,
			HttpServletRequest req) {
		boolean exist = false;
		UserInfo user = new UserInfo();
		user.setGoodsCategoryId(brandId);
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(Constant.QUERY_BRAND_BY_ID);
		head.setIp(req.getRemoteAddr());
		head.setUserId(userNo);
		SocketDTO dto = super.send(head, user);
		if (Constant.SUCCESS.equals(dto.getHead().getResponseCode())) {
			exist = true;
		}
		return exist;
	}

}
